package com.forum.impl.talk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.ApiResult;
import com.common.utils.LocalContext;
import com.common.vo.TalkPostsReplyInfoVo;
import com.forum.mapper.forum.ForumUserMapper;
import com.forum.mapper.talk.TalkPostsCommentReplyMapper;
import com.forum.param.TalkPostsCommentReplyQueryParam;
import com.forum.pojo.forum.ForumUser;
import com.forum.pojo.talk.TalkPostsCommentReply;
import com.forum.service.talk.TalkPostsCommentReplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tsing
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TalkPostsCommentReplyServiceImpl extends ServiceImpl<TalkPostsCommentReplyMapper, TalkPostsCommentReply> implements TalkPostsCommentReplyService {
    private final TalkPostsCommentReplyMapper replyMapper;
    private final ForumUserMapper userMapper;

    @Override
    public ApiResult<String> reply4Comment(TalkPostsCommentReply reply) {
        Integer currentUserId = LocalContext.getCurrentUserId();
        reply.setPublisherId(currentUserId);
        replyMapper.insert(reply);
        return ApiResult.success("操作成功");
    }

    @Override
    public ApiResult<Map<String, Object>> getReplyList(TalkPostsCommentReplyQueryParam queryParam) {
        List<TalkPostsCommentReply> replyList = replyMapper.getReplyList(queryParam.getCommentId(), (queryParam.getPage() - 1) * 10);
        Integer total = replyMapper.replyCount(queryParam.getCommentId());
        List<TalkPostsReplyInfoVo> collect = replyList.stream().map(reply -> {
            TalkPostsReplyInfoVo replyInfoVo = new TalkPostsReplyInfoVo();
            BeanUtils.copyProperties(reply, replyInfoVo);
            ForumUser publisherUser = userMapper.selectById(reply.getPublisherId());
            replyInfoVo.setNickname(publisherUser.getNickname());
            replyInfoVo.setAvatar(publisherUser.getAvatar());
            ForumUser parentUser = userMapper.selectById(reply.getParentUserId());
            replyInfoVo.setParentNickname(parentUser.getNickname());
            return replyInfoVo;
        }).collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>(16);
        map.put("total",total);
        map.put("list",collect);
        return ApiResult.success(map);
    }
}
